﻿# MS style build number (number of days since 2000)
# NOTE: Should probably be UTC
function _get-buildnumber() { [string](((Get-Date) - (Get-Date 2000/01/01)).Days) }

# MS style revision number (number of seconds / 2 since midnight)
# NOTE: Should probably be UTC...
function _get-revisionnumber() { [string]([int] (((get-date) - (get-date (Get-Date).Date)).TotalSeconds / 2)) }

# the nuget spec file
function _get-nuspec-path() { _build-abs-path .\migratorfoo_powershell.nuspec }

# nuget.exe path
function _get-nuget-exe() { _build-abs-path ..\..\tools\NuGet\NuGet.exe }

# this function is highly customized to the location
# of this build file, and the fact that it is NOT a module.
function _build-abs-path($rel_path) {
    $script_path = $MyInvocation.ScriptName
    
    $module_dir = Split-Path $script_path
    Join-Path $module_dir $rel_path
}

#
function _build-nuspec($releaseNotes = "") {
    
    $nuspec = [xml] (Get-Content $(_get-nuspec-path))
    $meta = $nuspec.package.metadata
    $meta.version = $meta.version.Replace("*", [string]$(_get-buildnumber) + "." + [string]$(_get-revisionnumber))
    
    if ([string]::IsNullOrEmpty($releaseNotes) -eq $false) {
        $meta.releaseNotes = $releaseNotes
    }
    
    $nuspec
}

function Invoke-BuildNuGetPackage {
    param($releaseNotes)
    
    # prepare the output dir
    $outDir = _build-abs-path .\bin
    if ((Test-Path $outDir) -eq $false) { New-Item $outDir -type directory }
    gci (join-path $outDir *) -include *.nupkg | ri
    
    # build the temp nuspec with correct version and release notes
    $tempNuSpecPath = _build-abs-path .\temp.nuspec
    if (Test-Path $tempNuSpecPath) { Remove-Item $tempNuSpecPath }
    $(_build-nuspec).Save($tempNuSpecPath)
    
    # pack
    & $(_get-nuget-exe) pack $tempNuSpecPath -OutputDirectory $outDir
    
    # clean up
    ri $tempNuSpecPath
} Export-ModuleMember Invoke-BuildNuGetPackage

<#
get-buildnumber
get-revisionnumber
get-releaseNotes
#>